package com.jinxin.platform.cdacsrecord.core.utils;

import com.jinxin.platform.cdacsrecord.core.pojo.vo.ResultVO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.*;
import org.springframework.util.MultiValueMap;
import org.springframework.web.client.RestTemplate;
import org.springframework.web.util.UriComponentsBuilder;

import java.util.*;

/**
 * All rights Reserved, Designed By www.beonelot.com
 *
 * @version: V1.0
 * @Copyright: www.beonelot.com Inc. All rights reserved.
 * @Description：
 * @Date: 2020-07-20
 * @Author: Lingnan
 **/
@Slf4j
public class RestTemplateUtils {

    /**
     * 向目的URL发送post请求
     * @param url       目的url
     * @param params    发送的参数
     * @return  ResultVO
     */
    public static ResultVO sendPostRequest(String url, MultiValueMap<String, Object> params){
        RestTemplate client = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        // 以表单的方式提交
        headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
        //将请求头部和参数合成一个请求
        HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(params, headers);
        //执行HTTP请求，将返回的结构使用ResultEntity类格式化
        ResponseEntity<ResultVO> response = client.postForEntity(url, requestEntity, ResultVO.class);

        return response.getBody();
    }

    public static <T> T sendRequest(String url, MultiValueMap<String, Object> params, Class<T> clazz, String type){
        RestTemplate client = new RestTemplate();
        HttpHeaders headers = new HttpHeaders();
        ResponseEntity<T> response;
        if("get".equalsIgnoreCase(type)){
            UriComponentsBuilder uriBuilder = UriComponentsBuilder.fromHttpUrl(url);
            Set<String> keySet = params.keySet();
            for (String key : keySet) {
                List<Object> values = params.get(key);
                if(values.size() > 0){
                    uriBuilder.queryParam(key,values.get(0));
                }
            }
            headers.setContentType(MediaType.APPLICATION_JSON_UTF8);
            HttpEntity<?> entity = new HttpEntity<>(headers);
            response = client.getForEntity(uriBuilder.build().encode().toUriString(), clazz, entity);
        }else if("post".equalsIgnoreCase(type)){
            // 以表单的方式提交
            headers.setContentType(MediaType.APPLICATION_FORM_URLENCODED);
            //将请求头部和参数合成一个请求
            HttpEntity<MultiValueMap<String, Object>> requestEntity = new HttpEntity<>(params, headers);
            //执行HTTP请求，将返回的结构使用ResultEntity类格式化
            response = client.postForEntity(url, requestEntity, clazz);
        }else {
            return null;
        }
        log.info("sendRequest:" + response.getBody().toString() );
        return response.getBody();
    }

}
